<template lang="html">
  <el-dialog :title="dialogTitle" :append-to-body="true" :close-on-click-modal="false" :show-close="false"
    v-model="dialogVisible" @close="close" width="600px">
    <i class="iconfont iconchahao-copy close_icon" @click="close"></i>
    <el-container v-loading="dialogLoading" class="task-setting-add-container">
      <el-main>
        <el-form label-width="125px" :model="taskSettingEntity" ref="settingForm" class="edit-pane" :inline="false"
          :rules="settingFormRules">
          <el-form-item label="任务Key" prop="id">
            <el-input v-model="taskSettingEntity.id" :disabled="isEdit" readonly style="width: 400px">
              <template #append>
                <el-select v-model="options.actionKeyOpts.current" placeholder="请选择" @change="onActionKeyChange"
                  :disabled="isEdit" style="width: 100px;">
                  <el-option v-for="item in options.actionKeyOpts.data" :key="item"
                    :label="`${item.taskCode}(${item.displayName})`" :value="item"></el-option>
                </el-select>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="任务名称" prop="displayName">
            <el-input v-model="taskSettingEntity.displayName" style="width: 400px"></el-input>
          </el-form-item>
          <el-form-item label="类型" prop="category" :required="true">
            <el-radio-group v-model="taskSettingEntity.category" size="large">
              <el-radio-button v-for="item in options.categorySelector" :key="item.value" :label="item.value">{{
                item.label }}</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="Command名称" prop="commandName">
            <el-input v-model="taskSettingEntity.commandName" style="width: 400px"></el-input>
          </el-form-item>
          <el-row>
            <el-col :span="8">
              <el-form-item label="是否允许重试" prop="isAllowRetry">
                <el-switch v-model="taskSettingEntity.isAllowRetry" size="large" @change="isAllowRetryChangeValue" />
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="taskSettingEntity.isAllowRetry">
              <el-form-item label="重试次数" prop="maxRetryCount">
                <el-input v-model.number="taskSettingEntity.maxRetryCount"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="超时时长(s)" prop="timeOutSecond">
            <el-input v-model.number="taskSettingEntity.timeOutSecond" style="width: 100px"></el-input>
          </el-form-item>
        </el-form>
      </el-main>
    </el-container>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">关闭</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="js">
import { onMounted, ref, inject } from 'vue';
import _ from 'lodash';
import { ElMessage } from 'element-plus';
import { numberRangeValidator, checkPsitiveInteger } from '@/utils/formVaildator';
import { getUnSettingActionKeys } from '@/api/taskSetting';
const { getMultiSelectOptions, selectNames } = inject('selectCollection');
const { onSuccess } = inject('taskSettingProvide');
import { createTaskCenterSetting, modifiedTaskCenterSetting } from '@/api/taskSetting';

const settingForm = ref(null);
const dialogVisible = ref(false); // 弹窗是否可见
const dialogLoading = ref(false); // 弹窗加载状态
const isEdit = ref(false); // 是否编辑状态
const dialogTitle = ref(""); // 弹窗标题
const initTaskSettingEntity = () => {
  return {
    id: '',
    displayName: '',
    category: '',
    commandName: '',
    isAllowRetry: false,
    maxRetryCount: 0,
    timeOutSecond: 0
  };
};
const taskSettingEntity = ref(initTaskSettingEntity());

const settingFormRules = {
  id: [{ required: true, message: "请输入配置Key", trigger: "change" }],
  displayName: [{ required: true, message: "请输入任务名称", trigger: "change" }],
  commandName: [{ required: true, message: "请输入Command", trigger: "change" }],
  maxRetryCount: [{ min: 1, max: 10, validator: numberRangeValidator, trigger: ["change", "blur"] }],
  timeOutSecond: [{ type: "number", validator: checkPsitiveInteger, trigger: ["change", "blur"] }],
  category: [{ required: true, message: "类型必选", trigger: ["change", "blur"] }],
  isAllowRetry: [{ required: true, message: "是否允许重试必选", trigger: ["change", "blur"] }]
}

/**
 * 初始化选项
 */
const options = ref({
  categorySelector: [],
  actionKeyOpts: {
    current: "",
    data: []
  }
});

function initInfos() {
  // 获取未配置的ActionKey
  getUnSettingActionKeys().then((res) => {
    if (!res.data || res.data.length === 0) {
      options.value.actionKeyOpts.data = [];
      return;
    }
    options.value.actionKeyOpts.data = res.data.map(item => ({
      taskCode: item.taskCode,
      displayName: item.displayName
    }));
  });
}

function initOptions() {
  // 加载枚举
  let keys = [selectNames.taskCenterCategoryEnum];
  getMultiSelectOptions(...keys).then((res) => {
    options.value.categorySelector = res.getOptions(selectNames.taskCenterCategoryEnum);
  });
}


// Method
function onActionKeyChange(newItem) {
  taskSettingEntity.value.id = newItem.taskCode;
  taskSettingEntity.value.displayName = newItem.displayName;
}

/**
 * 是否允许重试值变化
 * @param newValue 是否允许重试
 */
function isAllowRetryChangeValue(newValue) {
  if (newValue) {
    settingFormRules.maxRetryCount = [
      { required: true, type: "number", message: "请正确输入重试次数", trigger: ["change", "blur"] },
      { min: 1, max: 10, validator: numberRangeValidator, trigger: ["change", "blur"] }
    ];
  } else {
    settingFormRules.maxRetryCount = [{ min: 1, max: 10, validator: numberRangeValidator, trigger: ["change", "blur"] }];
  }
}

/**
 * 关闭弹窗
 */
function close() {
  if (dialogLoading.value) {
    return false;
  }
  dialogVisible.value = false;
  taskSettingEntity.value = initTaskSettingEntity();
}

/**
 * 保存
 */
function save() {
  dialogLoading.value = true;
  saveDebounce();
}

/**
 * 保存防抖
 */
const saveDebounce = _.debounce(() => {
  settingForm.value.validate((vaild) => {
    if (!vaild) {
      dialogLoading.value = false;
      ElMessage.error("数据验证不通过，请检查输入!");
      return;
    }
    let params = Object.assign({}, taskSettingEntity.value);

    params.maxRetryCount = params.isAllowRetry && params.maxRetryCount ? params.maxRetryCount : 0;

    let fun = isEdit.value ? modifiedTaskCenterSetting : createTaskCenterSetting;

    fun(params).then((res) => {
      if (res == null || !res.isSuccess) {
        ElMessage.error(res.message || "操作失败");
        return;
      }
      ElMessage.success("保存成功");
      dialogLoading.value = false;
      onSuccess();
      close();
    }).finally(() => {
      dialogLoading.value = false;
    });
  });


}, 300);

/**
 * 打开弹窗
 * @param item 任务设置项
 */
function open(item) {
  dialogLoading.value = false;
  options.value.actionKeyOpts.data = [];
  options.value.actionKeyOpts.current = {};
  if (settingForm.value) {
    settingForm.value.resetFields();
  }
  if (item && item.id) {
    dialogTitle.value = "编辑任务设置";
    taskSettingEntity.value = Object.assign({}, item);
    options.value.actionKeyOpts.current = {
      taskCode: item.id,
      displayName: item.displayName
    };
    isAllowRetryChangeValue(!!item.isAllowRetry);
    isEdit.value = true;
  } else {
    dialogTitle.value = "新增任务设置";
    isEdit.value = false;
    taskSettingEntity.value = initTaskSettingEntity();
  }

  initInfos();

  dialogVisible.value = true;
}

// 生命周期
onMounted(() => {
  initOptions();
  initInfos();
});

defineExpose({
  openDialog: open,
});
</script>
<style lang="less">
.task-setting-add-container .el-switch--large {
  height: 32px !important;
}
</style>
